<?php
class User_model extends MY_Model {
	public function __construct() {
		parent::__construct();
	}

    /**
     * 添加用户
     * @author  KevinBai
     * @return  boolean
     */
	public function add_user($data = array())
    {
        //检查用户是否存在
        if($this->check_user($data['username']))
        {
            return false;exit;
        }
        $AccountID = "MX_".substr(md5($data['username']),0,13) ;
        $data_final=array(
            'username'=>$data['username'],
            'password'=>md6($data['password']),
            'createtime'=>time(),
            'AccountID'=>$AccountID,
            'nickname'=>$AccountID,
            'tel'=>$data['username']
        );
        $res=$this->db->insert('blues_user',$data_final);
        $uid = $this->db->insert_id();
        if($res)
        {
            //生成token
            $this->load->library("Des3");
            $des3 = new Des3();
            $token = $des3->encrypt($data['username'].time());
            $this->db->insert("blues_token",array("AccountID"=>$AccountID,"token"=>$token));
            
            return array("AccountID"=>$AccountID,"token"=>$token);exit();
        }
        return false;
    }

    public function add_thirdUser($data = array())
    {
        //检查用户是否存在
        if($this->check_user($data['username']))
        {
            return false;exit;
        }
        $AccountID = "MX_".substr(md5($data['username']),0,13) ;
        $data_final=array(
            'username'=>$data['username'],
            'password'=>md6($data['password']),
            'createtime'=>time(),
            'AccountID'=>$AccountID,
            'nickname'=>$data['nickname'],
            'avatar'=>$data['headimgurl'],
            'tel'=>$data['username']
        );

        $res=$this->db->insert('blues_user',$data_final);
        $uid = $this->db->insert_id();
        $thirdData = [
                    'AccountID'=>$AccountID, 
                    'thirdPartyId'=>$data['openid'],
                    'type'=>$data['type'],
                    ];
        if($data['type'] == 'wechat')
        {
            $thirdData['unionid'] = $data['unionid'];    
        }            
        $this->db->insert('blues_third_login',$thirdData);
        if($res)
        {
            //生成token
            $this->load->library("Des3");
            $des3 = new Des3();
            $token = md5($des3->encrypt($data['username'].time()));
			$this->db->where('AccountID',$AccountID);
			$query = $this->db->get("blues_token");
			if($query->row_array())
			{
				$this->db->where('AccountID',$AccountID);
				$this->db->update("blues_token",array("token"=>$token));
			}else{
				$this->db->insert("blues_token",array("AccountID"=>$AccountID,"token"=>$token));
			}
            
            
            return array("AccountID"=>$AccountID,"token"=>$token);exit();
        }
        return false;
    }

    /**
     * 修改用户信息
     * @author  KevinBai
     * @param   int     $id     用户ID
     * @param   array   $data   修改数据
     * @return  boolean
     */
    public function edit_user($id,$data)
    {
        $this->db->where('AccountID',$id);
        return $this->db->update('blues_user',$data);
    }

    /**
     * 根据Username修改用户信息
     * @author  KevinBai
     * @param   array   $data   修改数据
     * @return  boolean
     */
    public function edit_user_by_username($username,$data)
    {
        $this->db->where('Username',$username);
        return $this->db->update('blues_user',$data);
    }

    /**
     * 退出
     * @author  KevinBai
     * @param   int     $id     用户ID
     * @param   array   $data   修改数据
     * @return  boolean
     */
    public function logout($AccountID)
    {
        $this->db->where('AccountID',$AccountID);
        return $this->db->update('blues_token',array("token"=>''));
    }
    /**
     * 删除用户
     * @author
     */
    public function del_user($uid)
    {
		$this->db->where('id', $uid);
		$res = $this->db->delete('blues_user');
		return $res;
    }

    /**
     * 用户登录
     * @auther  KevinBai
     * @param   string  $login_name 登录名
     * @param   string  $password   密码
     * @param   int     $save_type  保存类型
     * @return  array
     */
    public function login($login_name,$password)
    {
        //验证用户名是否存在

        $where=array("username"=>$login_name);

        $res = $this->db->get_where('blues_user',$where);
        
        if($res->num_rows()==0)
        {
            return 50013;
        }
        $where['password']=md6($password);
        $this->db->select('AccountID, username, nickname,avatar,tel,sex,region,Status');
		$query = $this->db->get_where('blues_user',$where);
        $result = $query->row_array();
		if(count($result) > 0)
		{
            if($result['Status'] == 1){
                return 50012;exit;
            }
            if($result['Status'] == -1){
                return 50013;exit;
            }
            //登录成功，生成秘钥token
			$row = $query->row();
            $this->load->library("Des3");
            $token = md5($row->username.time());
            
            $result['token'] = $token;
            if($result['avatar']){
                $result['avatar'] = OSSHOST.'upload/'.$result['avatar'];
            }
            $sql = "INSERT INTO blues_token (AccountID) VALUES ('".$result['AccountID']."') ON DUPLICATE KEY UPDATE token='{$token}'";
            $this->db->query($sql);
			return $result;exit();
		}
		return false;
    }

    public function sns_login($params = [])
    {
        $where = '';
        if($params['type'] == "wechat")
        {
            $where .= " AND t.unionid = '{$params["unionid"]}' ";
        }
        $sql = "SELECT u.AccountID,u.Status,t.type,u.nickname,u.avatar FROM blues_third_login t, blues_user u WHERE u.AccountID = t.AccountID AND  t.thirdPartyId='{$params["openid"]}' {$where}";
        $query = $this->db->query($sql);
        $result = $query->row_array();
        if(count($result) > 0)
        {
			if($result['Status'] == 1){
                return 50012;exit;
            }
            if($result['Status'] == -1){
                return 50013;exit;
            }
            $row = $query->row();
            $this->load->library("Des3");
            $token = md5($row->AccountID.time());
            $this->db->where("AccountID",$result['AccountID']);
            $this->db->update("blues_token",array("token"=>$token));
            $result['token'] = $token;
            return $result;exit();
    
        }
        return false;
    }

    public function saveSmsStatus($mobile,$data = array(), $sendCnt){
        //检查账户是否存在
        $existInfo = $this->check_sms_exist($mobile);
        if($existInfo){
            //执行编辑
            if($existInfo['currentday'] == date("Y-m-d",time()) && $existInfo['currentsentcnt'] < $sendCnt){
                $data['currentsentcnt'] = $existInfo['currentsentcnt']+1;
            }else{
               $data['currentday'] = date("Y-m-d",time()); 
            }
            $this->db->where("username",$mobile);
            $res = $this->db->update("blues_sms_token",$data);
        }else{
            //执行插入
            $data['currentsentcnt'] = 1;
            $data['currentday'] = date("Y-m-d",time());
            $data['username'] = $mobile;
            $res = $this->db->insert("blues_sms_token",$data);
        }
        return $res;
    }

    //判断注册发送手机号数目
    public function checkSendCnt($reginMobile, $sendCnt){
        $existInfo = $this->check_sms_exist($reginMobile);
        if($existInfo['currentsentcnt'] >= $sendCnt){
            return false;
        }else{
            return true;
        }
    }

    //根据账号获取短信验证token表信息
    public function get_mcodeInfo($mobile){
        $this->db->where("username",$mobile);
        $query = $this->db->get("blues_sms_token");
        return $query->row_array();
    }

    //根据token值获取用户信息
    public function getUserInfoByToken($token){
        $sql = "SELECT blues_user.* FROM blues_user,blues_token WHERE blues_user.AccountID=blues_token.AccountID AND blues_token.token='".$token."'";
        $query = $this->db->query($sql);
        return $query->row_array();
    }

    //验证token值是否合法
    public function checkToken($token){
        $current_time = time();
        //$sql = "SELECT count(*) cnt FROM blues_token WHERE token = '{$token}' AND expiretime > {$current_time}";
        $sql = "SELECT count(*) cnt FROM blues_token WHERE token = '{$token}'";
        $query = $this->db->query($sql);
        return $query->row_array()['cnt'];
    }

    /**
     * 根据uid获取用户信息
     */
    public function get_userinfo($uid, $login_name)
    {
    	if (!empty($uid))
    	{
    		$this->db->where('AccountID',$uid);
    	}
    	if (!empty($login_name))
    	{
	        $this->db->where('username',$login_name);
    	}
    	$query = $this->db->get('blues_user');
    	return $query->row_array();
    }
    //--------------------------------------------------------------------------


    /**
     * 检查sms_token表中是否有信息
     * @author  KevinBai
     * @param   string  $name   用户名
     * @param   int     $type   类型(0:用户名,1:邮箱)
     * @return  boolean
     */
    public function check_sms_exist($mobile)
    {
        $this->db->where("Username",$mobile);
        $query = $this->db->get('blues_sms_token');
        $res = $query->row_array();
        return $res; 
    }

    /**
     * 根accountid获取token值
     * @author  KevinBai
     * @param   string  $name   用户名
     * @return  boolean
     */
    public function getTokenByid($AccountID)
    {
        $this->db->where("AccountID",$AccountID);
        $query = $this->db->get('blues_token');
        $res = $query->row_array();
        return $res;
    }

    public function get_login_status($token = ""){
        if(empty($token)){
           return false;
        }
        $sql = "SELECT * FROM blues_token WHERE token = '{$token}'";
        $query = $this->db->query($sql);
        return $query->row_array();
    }

    /**
     * 检查用户是否存在
     * @author  nmx
     * @param   string  $name   用户名
     * @param   int     $type   类型(0:用户名,1:邮箱)
     * @return  boolean
     */
    public function check_user($mobile)
    {
        //验证用户名是否存在

        $this->db->where("username",$mobile);
        $res = $this->db->get('blues_user');
        if($res->num_rows()==0)
        {
            return FALSE;
        }
        return TRUE;
    }

    public function check_bind_status($params = [])
    {
        $this->db->where("username",$params['reginMobile']);
        $user = $this->db->get('blues_user');
        $result = ['isRegistMobile'=>true,'isbind'=>true];
        if($user->num_rows()==0)
        {
            $result['isRegistMobile'] = false;;
        }
        $where = '';
        if($params['type'] == "wechat")
        {
            $where .= " AND t.unionid = '{$params["unionid"]}' ";
        }
        $sql = "SELECT count(*) cnt FROM blues_third_login t, blues_user u WHERE u.AccountID = t.AccountID AND  t.thirdPartyId='{$params["openid"]}' {$where}";

        $query = $this->db->query($sql);
        $row = $query->row_array();
        if($row['cnt'] == 0)
        {
            $result['isbind'] = false;
        }

        return $result; 
    }


    

    /**
     * 获取用户信息
     * @author  KevinBai
     * @param   int $uid    用户ID
     * @return  array
     */
    public function get_userinfo_by_id($AccountID,$fields = " * ")
    {
        $sql = "SELECT  {$fields} FROM blues_user u WHERE AccountID = '{$AccountID}'";
        $query = $this->db->query($sql);
            $res=$query->row_array();
            return $res;
    }


     public function get_userinfo_by_keyword($keyword,$fields = " * ")
    {
        $sql = "SELECT  {$fields} FROM blues_user u WHERE AccountID = '{$keyword}' OR Username = '{$keyword}'";
        $query = $this->db->query($sql);
            $res=$query->row_array();
            return $res;
    }
  
    /**
     *
     * 通过用户名获取用户信息
     */
	public function get_userinfo_by_username($username)
	{
        $sql = "SELECT  u.* ,b.name,b.avatar,b.company FROM blues_user WHERE u.AccountID = b.AccountID AND u.Username = {$username}";
		$query = $this->db->query($sql);
        if($query->num_rows()>0)
        {
            $res=$query->row_array();
		    return $res;
        }
		return null;
	}


    /**
     *
     * 通过用户名获取用户信息
     */
    public function get_userinfo_by_accountids($AccountIDs,$fields = " * ",$keyword = "")
    {
        $where = " ";
        if($keyword){
            $where .= " AND Username like '%{$keyword}%' OR NickName like '%{$keyword}%' OR email LIKE  '%{$keyword}%'" ;
        }
        $sql = "SELECT  {$fields} FROM blues_user  WHERE AccountID  in ({$AccountIDs}) {$where}";
        $query = $this->db->query($sql);
        
        return $query->result_array();
    }

    /**
	 * 根据用ID获取找回密码信息
	 * @param String $uid 用户ID
	 */
	function get_forgotpwd_info($uid,$type=0)
	{
		if(empty($uid))
		{
			return false;
		}
		$query = $this->db->get_where('blues_user_forgotpass', array('uid' => $uid,'type'=>$type), 1, 0);
		if ($query->num_rows() > 0){
			return $query->row_array();
		}
		return false;
	}

    /**
	 * 更新找回密码表
	 * @param String   $uid    用户ID
	 * @param int      $expire 过期时间
	 * @param String   $mkey   用户密钥
	 * @return boolean
	 */
	function update_forget_pwd($uid,$expire,$mkey,$type=0) {
		$query = $this->db->get_where('blues_user_forgotpass', array('uid' => $uid,'type'=>$type), 1, 0);
		$this->db->order_by("expire","DESC");
		$data = array('uid'=>$uid,'expire'=>$expire,'authen'=>$mkey,'type'=>$type);
		if ($query->num_rows() > 0){
			//Update
			$info = $query->row_array();
		    $this->db->where('uid',$info['uid']);
		    $this->db->update('blues_user_forgotpass',$data);
		}else{
			//Insert
			$this->db->insert('blues_user_forgotpass',$data);
		}
		return $this->db->affected_rows()>0;
	}

    /**
	 * 重置密码
	 * @param int $uid
	 * @return string|boolean
	 */
	function reset_password($uid,$newpassword) {
		$this->load->helper('md6');
		$uid=intval($uid);
		$newpassword=md6($newpassword);
		$sql="update blues_user set password='{$newpassword}' where id={$uid}";
		return $this->db->query($sql);
	}

	/**
	 * 检测用户名是否重复
	 *
	 * @param string $username
	 * @return int
	 */
	public function check_username($AccountID='')
	{

		$sql = "SELECT * FROM blues_user WHERE AccountID='{$AccountID}';";

		$query = $this->db->query($sql);

		return $query->num_rows();
	}

    //通过环信获取好友列表
    public function getFriendList($AccountID){
        $this->load->library('Easemob');
        $Easemob = new Easemob();
        $data = $Easemob->showFriend($AccountID);
        $info = json_decode($data,1);
        return $info['data'];

    }

    public function getProtocol(){
        $sql = "SELECT content from blues_protocol";
        $query = $this->db->query($sql);
        $res = $query->result_array();
        return $res[0];
    }

    public function addPoints($AccountID, $data = array()){
        $sql = "SELECT points, createtime FROM blues_member_points WHERE AccountID = '{$AccountID}' ORDER BY createtime DESC";
        $query = $this->db->query($sql);
        $result = $query->result_array();
        if(isset($result) && $result[0]['createtime'] == date('Y-m-d',time())){
            return "hassignin";
        }else{
            //插入
            $this->db->where("AccountID", $AccountID);
            $res = $this->db->insert("blues_member_points",$data);
        }
        return $res;
    }



    public function getPointRecord($AccountID, $fields = " * ")
    {
        $sql = "SELECT {$fields} FROM blues_member_points WHERE points>0 AND (AccountID = '{$AccountID}') OR (toAccountID = '{$AccountID}') ORDER BY id DESC";
        $query = $this->db->query($sql);
        $result = $query->result_array();
        return $result;
    }

    public function getMoneyRecord($AccountID, $fields = " * ")
    {
        $sql = "SELECT {$fields} FROM blues_member_money WHERE money>0 AND (AccountID = '{$AccountID}') ORDER BY id DESC";
        $query = $this->db->query($sql);
        $result = $query->result_array();
        return $result;
    }

    public function hasSetPoint($AccountID){
		$today_time = date('Y-m-d',time());
        $sql = "SELECT count(*) cnt ,createtime FROM blues_member_points WHERE AccountID = '{$AccountID}' AND createtime='{$today_time}'";
        $query = $this->db->query($sql);
        $rows = $query->row_array();
        if($rows['cnt']){
            if($rows['createtime'] == date('Y-m-d',time())){
                return 1;
            }else{
               return 0;
            }
            
        }else{
            return 0;
        }
    }

    public function getOrderList($AccountID){

        $this->db->where(array("AccountID"=>$AccountID,"isDel"=>0));
        $query = $this->db->get("blues_goods_orders");
        $res = $query->result_array();
        return $res;
    }


    public function setRemarkNickname($fromAccountID, $toAccountID, $data = array()){
        $this->db->where(array('fromAccountID'=>$fromAccountID,'toAccountID'=>$toAccountID));
        $query = $this->db->get("blues_set_remark_nickname");
        $row = $query->row_array();
        if($row){
            //更新
            $this->db->where(array('fromAccountID'=>$fromAccountID,'toAccountID'=>$toAccountID));
            $res = $this->db->update("blues_set_remark_nickname",$data);
            
        }else{
            //插入
            $data['fromAccountID'] = $fromAccountID;
            $data['toAccountID'] = $toAccountID;
            $res = $this->db->insert("blues_set_remark_nickname",$data);
        }

        return $res;
    }

    public function getMysetRemarkNickname($fromAccountID,$toAccountID){
        $this->db->where(array('fromAccountID'=>$fromAccountID,'toAccountID'=>$toAccountID));
        $query = $this->db->get("blues_set_remark_nickname");
        return $query->row_array();

    }


    public function getMyCollection($data,$fromUsername,$per_page, $limit, $filds="*"){
        if($per_page){
            $per_page = ($per_page-1)*$limit;
        }
        $where = " ";
        if($data['keyword'])
        {
            $where .= " AND (n.content like '%{$data['keyword']}%' OR n.title like '%{$data['keyword']}%')";
        }
        $limit = " limit {$per_page},{$limit}";
        $sql = "SELECT c.id,c.status,c.fromUsername,c.createtime, n.newsID,n.title,n.transferfrom,n.addtime,n.cover FROM blues_news_collect c,blues_news n WHERE c.newsID=n.newsID AND c.fromUsername='{$fromUsername}' {$where} ORDER BY createtime DESC {$limit} ";
        $query = $this->db->query($sql);
        $result = $query->result_array();
        return $result;
    }

public function toShareGetPoints($data = array()){
        $this->db->trans_start();
        $res = $this->db->insert("blues_share_log",$data);
        $this->db->where(array("AccountID"=>$data['AccountID'],"createtime"=>$data['createtime']));
        $query = $this->db->get("blues_share_log");
        $num_rows = $query->num_rows();
        if($num_rows >=2){

        }else{
            $this->db->where("AccountID",$data['AccountID']);
            $query2 = $this->db->get("blues_member_points");
            $row2 = $query->row_array();
            if($row2){
            $sql = " update blues_member_points set points = points+5,createtime='{$data['createtime']}' where AccountID='{$data['AccountID']}'";
                $res = $this->db->query($sql);
            }else{
                $member_points = array(
                        'points'=>$recharge_money,
                        'AccountID'=>$data['AccountID'],
                        'createtime'=>$data['createtime']
                );
                $res = $this->db->insert("blues_member_points",$member_points);
            }

        }
        
        $this->db->trans_complete();
        return $res;
    }

 public function toRecharge($data = array()){
        $this->db->trans_start();
        $res = $this->db->insert("blues_recharge",$data);
        $recharge_money = 0;
        if($data['recharge_money']){
            $recharge_money =  $data['recharge_money']*100;
        }
        if($res){
           $createtime = date('Y-m-d',time());
	    $this->db->where("AccountID",$data['AccountID']);
            $query = $this->db->get("blues_member_points");
            $row = $query->row_array();
            if($row){
            $sql = " update blues_member_points set points = points+{$recharge_money},createtime='{$createtime}' where AccountID='{$data['AccountID']}'";
                $res = $this->db->query($sql);    
            }else{
		$member_points = array(
			'points'=>$recharge_money,
			'AccountID'=>$data['AccountID'],
			'createtime'=>$createtime
		);
                $res = $this->db->insert("blues_member_points",$member_points);
            }
            
        }
        $this->db->trans_complete(); 
        return $res;
    }

    /**
     * 执行绑定手机号
     * @return [type] [description]
     */
    public function bingPhone($params = [])
    {
        $data = [
            'AccountID'=>$params['AccountID'],
            'thirdPartyId'=>$params['openid'],
            'type'=>$params['type'],
            'nickname'=>$params['nickname'],
            'headimgurl'=>$params['headimgurl'],
        ]; 
        if($params['type'] == "wechat")
        {
            $data['unionid'] = $params['unionid'];
        }

         //生成token
        $this->load->library("Des3");
        $des3 = new Des3();
        $userInfo = $this->get_userinfo_by_id($data['AccountID'],"username");
        $token = $des3->encrypt($userInfo['username'].time());
        $res = $this->db->insert("blues_third_login", $data);

        return array("AccountID"=>$data['AccountID'],"token"=>$token);
    }

}



